package com.jxs.android.ges;

import java.io.IOException;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.jxs.android.ges.data.UserInfo;
import com.jxs.android.ges.data.VisitRecordInfo;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.HandlerHolder;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
public class Visit_Records_Detail extends AbstractActivity {
	// 2.4.6 getSmsContent 【获取发送页面内容】
	private BuLoadingDailog progressDialog;
	private String record_id = "";
	private TextView staff_name, industry_type_name, cust_name, create_date, update_date;
	private EditText basic;
	private CheckBox way_phone, way_site;

	private VisitRecordInfo visitRecordInfo;
	private int position;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		initTopBar(savedInstanceState, R.layout.bu_visit_records_detail);
		initUI();
		if (null != getIntent() && getIntent().hasExtra("record_id")) {
			record_id = getIntent().getStringExtra("record_id");
			position = getIntent().getIntExtra("position", 0);
		}
		getVisitsRecordXDetail();
	}

	private void initUI() {
		staff_name = (TextView) findViewById(R.id.staff_name);
		industry_type_name = (TextView) findViewById(R.id.industry_type_name);
		cust_name = (TextView) findViewById(R.id.cust_name);
		create_date = (TextView) findViewById(R.id.create_date);
		create_date.setBackgroundDrawable(null);
		update_date = (TextView) findViewById(R.id.update_date);
		basic = (EditText) findViewById(R.id.basic);
		basic.setEnabled(false);
		basic.setFocusable(false);
		way_phone = (CheckBox) findViewById(R.id.way_phone);
		way_site = (CheckBox) findViewById(R.id.way_site);
		way_phone.setClickable(false);
		way_site.setClickable(false);

	}

	private TopBar topBar;

	@Override
	public void topBarLogic(TopBar topBar) {
		this.topBar = topBar;
		// SpinnerButton FilterView Button
		topBar.setSpinnerBtnText("修改");
		topBar.setFilterBtnText("删除");
		topBar.setLogicBtnText("点评");
		topBarReturn(topBar);
		topBar.showAllBtn();
		topBar.hindLogicBtn();
		topBar.setTitle("走访记录详情");
		this.topBar.setBtnListern(btnListern);
	}

	public void topBarReturn(TopBar topBar) {
		if (null != topBar) {
			topBar.setTopBarReturnListern(new TopBar.ReturnBtnListern() {
				@Override
				public void onClickReturn() {
					edited();
				}
			});
		}
	}

	private TopBar.BtnListern btnListern = new TopBar.BtnListern() {

		@Override
		public void onSpinnerBtn() {// 修改
			isEdited = false;
			Intent intent = new Intent(Visit_Records_Detail.this, Visit_Records_Edit.class);
			Bundle bundle = new Bundle();
			bundle.putString("record_id", record_id);
			bundle.putInt("postition", position);
			intent.putExtras(bundle);
			startActivityForResult(intent, REQ_EDIT);
		}

		@Override
		@Deprecated
		public void onLogicBtn() {
		}

		@Override
		public void onFilterBtn() {// 删除
			showDelete();
		}
	};

	private final int REQ_EDIT = 0xac01;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == REQ_EDIT && resultCode == RESULT_OK) {
			isEdited = true;
			basic.setText(data.getExtras().getString("basic"));
		}
	}

	private void showDelete() {

		BuAlertDailog.builder(this, "提示", "确认删除吗？", new BuAlertDailog.AlertOkAndCancelListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.cancel();
				progressDialog.show();
				new Visit_Records_DeleteHolder(handler, record_id).deleteVisitesRecordX(GesApplication.getUserInfo().getTicket());
			}

			@Override
			public String getOkText(Context context) {
				return "删除";
			}

			@Override
			public String getCancleText(Context context) {
				return getString(R.string.prompt_cancel);
			}

			@Override
			public void cancelLogic(Dialog dialog) {
				dialog.cancel();

			}
		}).show();

	}

	private void getVisitsRecordXDetail() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getVisitsRecordXDetail(GesApplication.getUserInfo().getTicket(), record_id);
			}
		}).start();
	}

	private void getVisitsRecordXDetail(String ticket, String record_id) {
		// 2.4.3 getSmsContent 【获取工作日志详单接口】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getVisitsRecordXDetail ";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("record_id", record_id);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = HandlerHolder.What.TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;

				UserInfo info = GesApplication.getUserInfo();
				info.setVrCanDelete(Boolean.valueOf(soapObject.getProperty("canDelete").toString()));
				info.setVrCanUpdate(Boolean.valueOf(soapObject.getProperty("canUpdate").toString()));
				msg.obj = (SoapObject) soapObject.getProperty("retMsg");
				handler.sendMessage(msg);
			}
		}
	}

	private final int UPDATE_LIST_UI = 0x101;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (!MemoryUtil.isCurrentActivity(Visit_Records_Detail.class)) {
				return;
			}

			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == UPDATE_LIST_UI) {

				UserInfo info = GesApplication.getUserInfo();
				if (!info.isVrCanDelete()) {
					topBar.hindFilter();
				}
				if (!info.isVrCanUpdate()) {
					topBar.hindSpinnerBtn();
					basic.setEnabled(false);
				}

				initContentData((SoapObject) msg.obj);
			} else if (msg.what == HandlerHolder.What.ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.VISIT_RECORDS_SAVE_RESLT_OK) {
				errorMsgPop("修改成功！", new BuAlertDailog.IPhoneAlertDailog() {

					@Override
					public String getOkText(Context context) {
						return getString(R.string.promp_confirm);
					}

					@Override
					public void okLogic(Dialog dialog) {
						dialog.cancel();
						edited();
					}
				});
			} else if (msg.what == HandlerHolder.What.VISIT_RECORDS_DELETE_RESLT_OK) {
				errorMsgPop("删除成功！", new BuAlertDailog.IPhoneAlertDailog() {

					@Override
					public String getOkText(Context context) {
						return getString(R.string.promp_confirm);
					}

					@Override
					public void okLogic(Dialog dialog) {
						dialog.cancel();
						Intent intent = new Intent();
						Bundle bundle = new Bundle();
						bundle.putInt("position", position);
						bundle.putBoolean("delete", true);
						intent.putExtras(bundle);
						setResult(RESULT_OK, intent);
						finish();
					}
				});
			}
		}
	};

	boolean isEdited = false;

	private void edited() {
		Intent intent = new Intent();
		Bundle bundle = new Bundle();
		bundle.putInt("position", position);
		bundle.putBoolean("edit", isEdited);
		bundle.putString("content", basic.getText().toString());
		intent.putExtras(bundle);
		setResult(RESULT_OK, intent);
		finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		return false;
	}

	private void initContentData(SoapObject retMsgObject) {
		if (null != retMsgObject) {
			visitRecordInfo = new VisitRecordInfo();
			visitRecordInfo.basic = SoapUtil.getValue(retMsgObject, "basic");// 拜访基本情况
			visitRecordInfo.create_date = SoapUtil.getValue(retMsgObject, "create_date");// 日期
			visitRecordInfo.today_content = SoapUtil.getValue(retMsgObject, "today_content");// 内容
			visitRecordInfo.cust_name = SoapUtil.getValue(retMsgObject, "cust_name");// 客户名称
			visitRecordInfo.cust_no = SoapUtil.getValue(retMsgObject, "cust_no");// 客户编号
			visitRecordInfo.industry_type_name = SoapUtil.getValue(retMsgObject, "industry_type_name");// 行业中心
			visitRecordInfo.record_id = SoapUtil.getValue(retMsgObject, "record_id");// 走访记录ID
			visitRecordInfo.staff_name = SoapUtil.getValue(retMsgObject, "staff_name");// 客户经理名称
			visitRecordInfo.staff_no = SoapUtil.getValue(retMsgObject, "staff_no");// 客户经理工号
			visitRecordInfo.update_date = SoapUtil.getValue(retMsgObject, "update_date");// 更新时间
			visitRecordInfo.way_phone = SoapUtil.getValue(retMsgObject, "way_phone");// 电话拜访（1选中，其他未选中）
			visitRecordInfo.way_site = SoapUtil.getValue(retMsgObject, "way_site");// 现场拜访（1选中，其他未选中）
			visitRecordInfo.week_desc = SoapUtil.getValue(retMsgObject, "week_desc");// 星期几
			initData();
		}
	}

	private void initData() {
		staff_name.setText(visitRecordInfo.staff_name);
		industry_type_name.setText(visitRecordInfo.industry_type_name);
		cust_name.setText(visitRecordInfo.cust_name);
		create_date.setText(visitRecordInfo.create_date + "\n" + visitRecordInfo.week_desc);
		update_date.setText("" + visitRecordInfo.update_date);
		basic.setText(visitRecordInfo.basic);
		if ("1".equals(visitRecordInfo.way_phone)) {
			way_phone.setChecked(true);
		}
		if ("1".equals(visitRecordInfo.way_site)) {
			way_site.setChecked(true);
		}

	}
}
